package com.pig.graduate.service.impl.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig.graduate.domain.sys.SysMenu;
import com.pig.graduate.service.sys.SysMenuService;
import com.pig.graduate.mapper.sys.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
* @author hp
* @description 针对表【sys_menu】的数据库操作Service实现
* @createDate 2023-01-14 10:58:07
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Autowired
    private SysMenuMapper menuMapper;

    /**
     * 构造菜单树
     * @param sysMenuList
     * @return
     */
    public List<SysMenu> buildTreeMenu(List<SysMenu> sysMenuList){
        List<SysMenu> resultMenuList = new ArrayList<>();

        for (SysMenu sysMenu : sysMenuList) {
            // 寻找子节点
            for (SysMenu e : sysMenuList) {
                if (e.getParentId()==sysMenu.getId()) {
                    sysMenu.getChildren().add(e);
                }
            }
            // 判断父节点，添加到集合
            if(sysMenu.getParentId()==0L){
                resultMenuList.add(sysMenu);
            }
        }
        return resultMenuList;
    }

    @Override
    public List<SysMenu> getMenuByRoleId(Integer roleId) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        List<SysMenu> list = menuMapper.selectList(queryWrapper);
        List<SysMenu> menuList = menuMapper.getMenuByRoleId(roleId);
        HashSet<SysMenu> set = new HashSet<>(menuList);
        for(int i = 0; i < list.size(); i++){
            if(!set.add(list.get(i))){
                list.get(i).setSelect(true);
            }
        }

        return this.buildTreeMenu(list);
    }
}




